<?php

namespace app\controllers;

use app\lib\BaseFunction;
use app\models\Bank_bill;
use app\models\Baoxiao;
use app\models\CommonModel;
use app\models\Customer;
use app\models\CustomerRefer;
use app\models\Department;
use app\models\Express;
use app\models\Income;
use app\models\Inland;
use app\models\Inquiry;
use app\models\InRepo;use app\models\InrepoEdit;use app\models\InrepoLock;use app\models\InrepoLog;use app\models\Invoice;use app\models\InvoiceLock;use app\models\Invoice_new;use app\models\ModelFactory;use app\models\PrintModel;
use app\models\Product;
use app\models\Purchase;
use app\models\Purchase_order;
use app\models\Rebate;
use app\models\Repo;
use app\models\RepoFeeVerify;
use app\models\Staff;
use app\service\FinanceService;
use app\service\IncomeService;
use app\service\InlandService;
use app\service\OrderService;
use yii;
use yii\data\Pagination;
use yii\helpers\Url;

class TableController extends CommonController
{
    public $layout = false;

    public $orderService;

    public function beforeAction($action)
    {
        $this->orderService = new OrderService();
        return parent::beforeAction($action);
    }

    public function actionIndex()
    {
        $year = yii::$app->request->get('year', date('Y'));
        //获取每月订单数量
        $model  = new Invoice_new();
        $list   = $model->getSumByYear($year);
        $column = array_column($list, 'm');
        $data   = array_column($list, 'num');
        $money  = array_column($list, 'money');
        $min    = array_column($list, 'min_money');
        $max    = array_column($list, 'max_money');
        return $this->render('index', ['min' => $min, 'max' => $max, 'money' => $money, 'list' => $list, 'column' => $column, 'data' => $data]);
    }

    //------------------------------------------------------------------收款开始
    public function actionIncome()
    {
        $p                      = is_numeric(yii::$app->request->get('page')) ? yii::$app->request->get('page') : 1;
        $s                      = is_numeric(yii::$app->request->get('per-page')) ? yii::$app->request->get('per-page') : 15;
        $where['pay_from']      = is_numeric(yii::$app->request->get('pay_type')) ? yii::$app->request->get('pay_type') : 0;
        $where['begin_time']    = yii::$app->request->get('begin_time');
        $where['end_time']      = yii::$app->request->get('end_time');
        $where['service_name']  = trim(yii::$app->request->get('service_name'));
        $where['number']        = trim(yii::$app->request->get('number'));
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['invocie_num']   = trim(yii::$app->request->get('invocie'));
        $where['property_p']    = yii::$app->request->get('property_p');

        $service = new IncomeService();
        $data    = $service->incomeList($p, $s, $where);
        $pages   = new Pagination(['totalCount' => (int) $data['size'], 'pageSize' => (int) $s]);

        return $this->render('income', ['pages' => $pages, 'data' => $data]);
    }

    /**校验金额是否正确
     * @param $pid
     */
    public function validateMoney($pid)
    {
        $model = new Income();
        $model->validateMoney($pid);
    }

    public function actionIncomeListV1()
    {
        $p                      = is_numeric(yii::$app->request->get('page')) ? yii::$app->request->get('page') : 1;
        $s                      = is_numeric(yii::$app->request->get('per-page')) ? yii::$app->request->get('per-page') : 15;
        $where['pay_from']      = is_numeric(yii::$app->request->get('pay_type')) ? yii::$app->request->get('pay_type') : 0;
        $where['begin_time']    = yii::$app->request->get('begin_time');
        $where['end_time']      = yii::$app->request->get('end_time');
        $where['service_name']  = trim(yii::$app->request->get('service_name'));
        $where['number']        = trim(yii::$app->request->get('number'));
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['invocie_num']   = trim(yii::$app->request->get('invocie'));
        $where['property_p']    = yii::$app->request->get('property_p');
        $service                = new IncomeService();
        $list                   = $service->apiList($p, $s, $where);
        return json_encode($list);
    }

    /**通用数据
     * @return string
     */
    public function actionIncomeBaseV1()
    {
        $service = new IncomeService();
        $list    = $service->incomeBase();
        return json_encode($list);

    }

    public function actionPaypal()
    {
        $p                      = is_numeric(yii::$app->request->get('page')) ? yii::$app->request->get('page') : 1;
        $s                      = is_numeric(yii::$app->request->get('per-page')) ? yii::$app->request->get('per-page') : 15;
        $where['pay_from']      = 1;
        $where['begin_time']    = yii::$app->request->get('begin_time');
        $where['end_time']      = yii::$app->request->get('end_time');
        $where['service_name']  = trim(yii::$app->request->get('service_name'));
        $where['number']        = trim(yii::$app->request->get('number'));
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['invocie_num']   = trim(yii::$app->request->get('invocie'));
        $where['property_p']    = yii::$app->request->get('property_p');

        $service = new IncomeService();
        $data    = $service->incomeList($p, $s, $where);
        $pages   = new Pagination(['totalCount' => (int) $data['size'], 'pageSize' => (int) $s]);

        return $this->render('income', ['pages' => $pages, 'data' => $data]);
    }

    /**
     * 添加一条拆分数据
     *
     */
    public function actionSplit_income_insert()
    {
        if (yii::$app->request->isPost) {
            $data['id']          = (int) yii::$app->request->post('id');
            $data['in_come']     = yii::$app->request->post('in_come');
            $data['total_fee']   = yii::$app->request->post('total_fee');
            $data['fee']         = yii::$app->request->post('fee');
            $data['invocie_num'] = yii::$app->request->post('invoice');
            $service             = new IncomeService();
            $re                  = $service->insert_split($data);
            $this->validateMoney($data['id']);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '拆分成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '拆分失败']);
            }
        }
    }

    /**
     * 删除收入报表数据
     */
    public function actionDel_income()
    {
        $id = yii::$app->request->post('id');
        if (empty($id) && is_int($id)) {
            return json_encode(['code' => 0, 'msg' => '参数错误']);
        }
        $model = new Income();
        if ($list = $model->all(['pid' => $id])) {
            if (count($list) > 1) {
                return json_encode(['code' => 0, 'msg' => '请先删除子项']);
            }
        }
        $info = $model->one(['id' => $id]);

        $arr           = [];
        $arr['url']    = 'del_income';
        $arr['staff']  = $this->user['job_number'];
        $arr['remark'] = '删除收入报表数据id' . yii::$app->request->post('id');
        BaseFunction::check_edit_auth($this->user['role']);
        BaseFunction::operation($arr);
        if ($id) {
            if ($model->delete(['id' => $id])) {
                $this->validateMoney($info['pid']);
                echo json_encode(['code' => 1, 'msg' => '删除成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '删除失败,请重试']);
            }
        }
    }

    /**修改记录
     * @return string
     */
    public function actionIncome_edit_by_cloumn()
    {
        BaseFunction::check_edit_auth($this->user['role']);
        $id     = yii::$app->request->post('id');
        $column = yii::$app->request->post('column');
        $value  = yii::$app->request->post('v');
//        if (!$id || !$column || !$value) {
        //            return json_encode(['code' => 0, 'msg' => '参数不全']);
        //        }
        if (is_numeric($id)) {
            $model = new Income();
            $re    = $model->save([$column => $value], ['id' => $id]);
            $info  = $model->one(['id' => $id]);
            $this->validateMoney($info['pid']);
            if ($re) {
                return json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                return json_encode(['code' => 0, 'msg' => '更新失败,请重试']);
            }
        }
    }

    //------------------------------------------------------------------------收款end

    //-------------------------------------------------------------------------支出开始
    /**
     * 银行报表
     */
    public function actionBank()
    {
        $p                      = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                      = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where['begin_time']    = yii::$app->request->get('begin_time');
        $where['end_time']      = yii::$app->request->get('end_time');
        $where['invocie']       = trim(yii::$app->request->get('invocie'));
        $where['number']        = trim(yii::$app->request->get('number'));
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['service_name']  = trim(yii::$app->request->get('service_name'));
        $where['money']         = trim(yii::$app->request->get('money'));
        $where['type']          = yii::$app->request->get('type');
        $where['product']       = yii::$app->request->get('product');
        $where['group']         = yii::$app->request->get('group') ? yii::$app->request->get('group') : "";
        $where['bank']          = yii::$app->request->get('bank');
        $where['type_child']    = yii::$app->request->get('type_child');
        $where['purchase_num']  = trim(yii::$app->request->get('purchase_num'));
        $model                  = new Bank_bill();
        $bank_type              = $model->get_bank_type();
        $size                   = $model->get_bank_bill_size($where);
        $chart                  = $model->getSumByType($where);
        array_push($bank_type, ['id' => 0, 'name' => '请选择']);
        $title = [];
        foreach ($chart as $k => $v) {
            foreach ($bank_type as $v2) {
                if ($v['type'] == $v2['id']) {
                    $title[]           = $v2['name'];
                    $chart[$k]['name'] = $v2['name'];
                }
            }
        }
        yii::$app->view->params['pagecount'] = $size;
        $page                                = $size ? ceil($size / $s) : 1;
        //部门列表
        $departmentModal = new Department();
        $group_list      = $departmentModal->all();
        //业务员列表
        $saleman_model = new Staff();
        $saleman_list  = $saleman_model->get_all_saleman();

        $list = $model->get_bank_bill_list($p, $s, $where);
        //校验银行支出客户信息是否正确
        $list = $this->validateBankCustomer($list);

        //数据统计
        $re                                     = $model->get_caculate_data($where);
        yii::$app->view->params['caculate_num'] = ['in_money' => $re['in_money'], 'out_money' => $re['out_money']];

        $base_url                               = $this->get_base_url();
        $base_url                               = Url::to(['table/bank']) . $base_url;
        yii::$app->view->params['group_list']   = $group_list;
        yii::$app->view->params['saleman_list'] = $saleman_list;
        yii::$app->view->params['bank_type']    = $bank_type;
        yii::$app->view->params['page']         = ['curr' => $p, 'page' => $page, 'base_url' => $base_url];
        yii::$app->view->params['list']         = $list;
        return $this->render('bank', ['title' => $title, 'chart' => $chart]);
    }

    public function actionBankList()
    {
        $p                      = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                      = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where['begin_time']    = yii::$app->request->get('begin_time');
        $where['end_time']      = yii::$app->request->get('end_time');
        $where['invocie']       = trim(yii::$app->request->get('invocie'));
        $where['number']        = trim(yii::$app->request->get('number'));
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['service_name']  = trim(yii::$app->request->get('service_name'));
        $where['money']         = trim(yii::$app->request->get('money'));
        $where['type']          = yii::$app->request->get('type');
        $where['type']          = !empty($where['type']) ? explode(',', $where['type']) : $where['type'];
        $where['product']       = yii::$app->request->get('product');
        $where['group']         = yii::$app->request->get('group') ? yii::$app->request->get('group') : "";
        $where['bank']          = yii::$app->request->get('bank');
        $where['type_child']    = yii::$app->request->get('type_child');
        $where['purchase_num']  = trim(yii::$app->request->get('purchase_num'));
        $model                  = new Bank_bill();
        $list                   = $model->get_bank_bill_list($p, $s, $where);
        $list                   = $this->validateBankCustomer($list);
        echo json_encode($list);

    }

    /**银行列表通用信息
     * @return string
     */
    public function actionBankBase()
    {
        $model     = new Bank_bill();
        $bank_type = $model->get_bank_type();
        array_push($bank_type, ['id' => 0, 'name' => '请选择']);
        $departmentModal = new Department();
        $group_list      = $departmentModal->all();
        //业务员列表
        $saleman_model = new Staff();
        $saleman_list  = $saleman_model->get_all_saleman();
        $bank          = yii::$app->params['bank'];
        return json_encode(['status' => 1, 'data' => [
            'bankType' => $bank_type,
            'bank'     => $bank,
            'group'    => $group_list,
            'staff'    => $saleman_list,
        ]]);

    }

    /**校验银行支出客户信息是否正确
     * @param $list
     * @return mixed
     */
    public function validateBankCustomer($list)
    {
        $customerArr = [];
        foreach ($list as $v) {
            $customerArr[] = $v['number'];
        }
        //判断客户编号和客户名称是否一致
        $customerModel = new Customer();
        $customerList  = $customerModel->getCustomerByNum($customerArr);

        foreach ($list as $k => $v) {
            if ($v['number'] && isset($customerList[$v['number']])) {
                if ($v['customer_name'] == $customerList[$v['number']]) {
                    $list[$k]['same'] = true;
                } else {
                    $list[$k]['same'] = false;
                }
            } else {
                $list[$k]['same'] = false;
            }

        }
        return $list;
    }

    /**
     * 编辑银行报表操作
     */
    public function actionBank_edit_by_column()
    {
        $id = yii::$app->request->post('id');
        if (is_numeric($id)) {
            $column = yii::$app->request->post('column');
            $value  = trim(yii::$app->request->post('v'));
            $model  = new Bank_bill();
            if ($model->save([$column => $value], ['id' => $id])) {
                $info = $model->one(['id' => $id]);
                $model->validateBankMoeny($info['pid']);
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败,请重试']);
            }
        }
    }

    public function actionBankEdit()
    {
        $rawBody = yii::$app->request->getBodyParams();
        var_dump($rawBody);
    }

    /**拆分银行报表
     * @return string
     */
    public function actionSplitBank()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法登录']);
        }
        $id = yii::$app->request->post('id');

        //复制一条记录
        $model = new Bank_bill();
        $info  = $model->one(['id' => $id]);
        if ($info['pid'] != $info['id']) {
            return json_encode(['code' => 0, 'msg' => '当前记录已经是拆分项了，无法继续拆分']);
        }
        $info['pid'] = $info['id'];
        unset($info['id']);
        //插入一条数据
        try {
            $re = $model->insert($info);
            if ($re) {
                $model->validateBankMoeny($info['pid']);
                return json_encode(['code' => 1, 'msg' => '拆分成功']);
            } else {
                return json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
            }
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return json_encode(['code' => 0, 'msg' => $msg]);
        }

    }

    public function actionDel_bank()
    {
        $id = yii::$app->request->post('id');
        if (empty($id) && $id !== 0) {
            return json_encode(['code' => 0, 'msg' => '参数不全']);
        }
        $model = new Bank_bill();
        //查询是否存在子项
        if ($list = $model->getListByPid($id)) {
            if (count($list) > 1) {
                return json_encode(['code' => 0, 'msg' => '请先删除子项']);
            }

        }
        $arr           = [];
        $arr['url']    = 'del_bank';
        $arr['staff']  = $this->user['job_number'];
        $arr['remark'] = '删除银行报表数据id' . yii::$app->request->post('id');
        BaseFunction::check_edit_auth($this->user['role']);
        BaseFunction::operation($arr);
        if ($id) {
            $info = $model->one(['id' => $id]);
            if ($model->delete(['id' => $id])) {
                $model->validateBankMoeny($info['pid']);
                echo json_encode(['code' => 1, 'msg' => '删除成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '删除失败,请重试']);
            }
        }
    }

    /**
     * 退税报表
     */
    public function actionRebate()
    {
        $p                   = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                   = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where['begin_time'] = yii::$app->request->get('begin_time') ? yii::$app->request->get('begin_time') : date('Y-m') . '-01';
        $where['end_time']   = yii::$app->request->get('end_time') ? yii::$app->request->get('end_time') : date('Y-m-d');
        $model               = new Rebate();
        if ($size = $model->get_rebate_size($where)) {
            $page = floor($size['num'] / $s) + 1;
        } else {
            $page = 1;
        }
        $list                           = $model->get_rebate_list($p, $s, $where);
        $base_url                       = Url::to(['table/rebate', 'begin_time' => $where['begin_time'], 'end_time' => $where['end_time']]);
        yii::$app->view->params['page'] = ['page' => $page, 'curr' => $p, 'base_url' => $base_url];
        yii::$app->view->params['list'] = $list;
        return $this->render('rebate');
    }

    /**
     *
     */
    public function actionDel_rebate()
    {
        $id = is_numeric(yii::$app->request->post('id')) ? yii::$app->request->post('id') : "";
        if ($id) {
            $model = new Rebate();
            if ($model->del_rebate_by_id($id)) {
                echo json_encode(['code' => 1, 'msg' => '删除成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '删除失败,请重试']);
            }
        }
    }
    //----------------------------------------------------------银行支出end

    //-----------------------------------------------------------国际快递单据start
    /**国家快递单据
     * @return string
     */
    public function actionExpress_list()
    {
        $p                        = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s                        = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;
        $where['begin_time']      = yii::$app->request->get("begin_time");
        $where['end_time']        = yii::$app->request->get("end_time");
        $where['express_id']      = yii::$app->request->get('express_id') ? yii::$app->request->get('express_id') : "";
        $where['name']            = yii::$app->request->get('name');
        $where['customer_name']   = trim(yii::$app->request->get('customer_name'));
        $where['customer_number'] = trim(yii::$app->request->get('customer_number'));
        $where['invoice']         = trim(yii::$app->request->get('invoice'));
        $where['tradeno']         = trim(yii::$app->request->get('tradeno'));
        $where['type']            = yii::$app->request->get('type');
        $fee                      = yii::$app->request->get("fee");
        if (!$fee) {
            $where['fee'] = 0;
        } else {
            $fee_arr      = explode("-", $fee);
            $where['fee'] = 1;
            if (count($fee_arr) == 1) {
                $where['begin_fee'] = 0;
                $where['end_fee']   = (float) $fee_arr[0];
            } else {
                $where['begin_fee'] = $fee_arr[0];
                $where['end_fee']   = $fee_arr[1];
            }
        }
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['name']                      = $this->user['job_number'];
            yii::$app->view->params['show_fee'] = false;
        } else {
            yii::$app->view->params['show_fee'] = true;
        }
        $model        = new Express();
        $express_type = $model->get_express_type();
        //费用总和
        $express_list                      = $model->get_express_list($p, $s, $where);
        $express_list                      = $this->validateExpressCustomer($express_list);
        $size                              = $model->get_express_size($where);
        $page                              = $size ? (ceil($size / $s)) : 1;
        $re                                = $model->get_caculate_data($where);
        yii::$app->view->params['pay_all'] = $re['pay_all'];

        $staff_model = new Staff();
        $staff_list  = $staff_model->get_all_saleman();

        yii::$app->view->params['staff_list']   = $staff_list;
        $base_url                               = Url::to(['table/express_list']) . $this->get_base_url();
        yii::$app->view->params['page']         = ['page' => $page, 'size' => $size, 'curr' => $p, 'base_url' => $base_url];
        yii::$app->view->params['express_type'] = $express_type;
        return $this->render('express_list', ['express_list' => $express_list, 'user' => $this->user]);
    }

    public function actionExpressList()
    {
        $p                        = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s                        = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;
        $where['begin_time']      = yii::$app->request->get("begin_time");
        $where['end_time']        = yii::$app->request->get("end_time");
        $where['express_id']      = yii::$app->request->get('express_id') ? yii::$app->request->get('express_id') : "";
        $where['name']            = yii::$app->request->get('name');
        $where['customer_name']   = trim(yii::$app->request->get('customer_name'));
        $where['customer_number'] = trim(yii::$app->request->get('customer_number'));
        $where['invoice']         = trim(yii::$app->request->get('invoice'));
        $where['tradeno']         = trim(yii::$app->request->get('tradeno'));
        $where['type']            = yii::$app->request->get('type');
        $model                    = new Express();
        $express_list             = $model->get_express_list($p, $s, $where);
        $size                     = $model->get_express_size($where);
        $express_list             = $this->validateExpressCustomer($express_list);
        return json_encode(['list' => $express_list, 'total' => $size]);
    }

    public function actionExpressBase()
    {
        $model        = new Express();
        $express_type = $model->get_express_type();
        $staff_model  = new Staff();
        $staff_list   = $staff_model->get_all_saleman();
        return json_encode(['express' => $express_type, 'staff' => $staff_list]);
    }

    public function validateExpressCustomer($express_list)
    {
        $arr           = array_column($express_list, 'customer_number');
        $customerModel = new Customer();
        $customerList  = $customerModel->getCustomerByNum($arr);
        foreach ($express_list as $k => $v) {
            if (isset($customerList[$v['customer_number']]) &&
                $v['customer_name'] == $customerList[$v['customer_number']]) {
                $express_list[$k]['same'] = true;
            } else {
                $express_list[$k]['same'] = false;
            }
        }
        return $express_list;
    }

    /**添加国际快递
     * @return string
     * @throws yii\db\Exception
     */
    public function actionAjax_add_express()
    {
        if (yii::$app->request->isGet) {
            $model                             = new ModelFactory();
            $express                           = $model->express();
            $list                              = $express->get_express_type();
            yii::$app->view->params['express'] = $list;
            return $this->render('ajax_add_express');
        } elseif (yii::$app->request->isPost) {
            $data                     = yii::$app->request->post('data');
            $data['name']             = $this->user['job_number'];
            $data['last_modify']      = $this->user['job_number'];
            $data['last_modify_time'] = time();
            $model                    = new Express();
            $re                       = $model->insert($data);
            $model->updatePid();
            if ($re) {
                return json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                return json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
            }
        } else {
            return json_encode(['code' => 0, 'msg' => '非法操作']);
        }
    }

    /**
     * 删除快递
     */
    public function actionExpress_del()
    {
        $id = yii::$app->request->post('id');
        if (!is_numeric($id)) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        $model = new Express();
        $info  = $model->one(['id' => $id]);
        //校验锁定状态
        if ($info['lock'] == 1) {
            return json_encode(['code' => 0, 'msg' => '已被锁定无法修改']);
        }

        //查询是否存在子项
        $list = $model->all(['pid' => $id]);
        if (count($list) > 1) {
            return json_encode(['code' => 0, 'msg' => '请先删除子项']);
        }
        $info = $model->one(['id' => $id]);
        if ($model->delete(['id' => $id])) {
            //删除之后验证费用是否相同
            if ($info['pid'] != $info['id']) {
                $model->validateExpressMoney($info['pid']);
            }
            $output = ['code' => 1, 'msg' => '删除成功'];
        } else {
            $output = ['code' => 1, 'msg' => '删除失败,请重试'];
        }
        echo json_encode($output);

    }

    public function actionUpdate_express()
    {
        $id = yii::$app->request->post('id');
        if (!is_numeric($id)) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }
        $model = new Express();
        $info  = $model->one(['id' => $id]);
        //校验锁定状态
        if ($info['lock'] == 1) {
            return json_encode(['code' => 0, 'msg' => '已被锁定无法修改']);
        }

        $column = yii::$app->request->post('column');
        $value  = trim(yii::$app->request->post('v'));
        //要修改的字段是invoice时需要先判断订单未结算才行
        if ($column == 'invoice_order') {
            //修改的invoice已经结算
            if ($this->orderService->isJiesuan(['invoice' => $value])) {
                return json_encode(['code' => 0, 'msg' => '需要修改的invoice已经结算']);
            }
        }
        $data                     = [];
        $data['last_modify']      = $this->user['job_number'];
        $data['last_modify_time'] = time();
        $data[$column]            = $value;
        if ($model->save($data, ['id' => $id])) {
            //更新拆分项金钱是否一致
            $info = $model->one(['id' => $id]);
            $model->validateExpressMoney($info['pid']);
            $output = ['code' => 1, 'msg' => '更新成功'];
        } else {
            $output = ['code' => 1, 'msg' => '更新失败,请重试'];
        }
        echo json_encode($output);

    }

    /**
     * 添加快递拆分项
     */
    public function actionExpressSplit()
    {
        if (yii::$app->request->isPost) {
            $id      = yii::$app->request->post('id');
            $invoice = yii::$app->request->post('invoice');
            $fee     = yii::$app->request->post('fee');
            //校验需要修改的invoice是否结算
            if ($invoice) {
                if ($this->orderService->isJiesuan(['invoice' => $invoice])) {
                    return json_encode(['code' => 0, 'msg' => '需要修改的invoice已经结算']);
                }
            }
            //先复制一条记录
            $model = new Express();
            $info  = $model->one(['id' => $id]);
            if ($info['lock'] == 1) {
                return json_encode(['code' => 0, 'msg' => '订单被锁定，无法拆分']);
            }
            //拆分项无法拆分
            if ($info['pid'] != $info['id']) {
                return json_encode(['code' => 0, 'msg' => '该条记录是拆分项，无法继续拆分']);
            }
            $info['pid'] = $info['id'];
            unset($info['id']);
            $info['invoice_order']    = $invoice;
            $info['fee']              = $fee;
            $info['split_status']     = 2;
            $info['last_modify_time'] = time();
            $info['last_modify']      = $this->user['job_number'];
            $re                       = $model->insert($info);
            $model->validateExpressMoney($info['pid']);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败']);
            }
        }
    }

    /**
     * 快递order锁定
     */
    public function actionExpressLock()
    {
        if (yii::$app->request->isPost) {
            $id   = yii::$app->request->post('id');
            $lock = yii::$app->request->post('lock');
            $re   = yii::$app->db->createCommand()->update(yii::$app->db->tablePrefix . 'express', ['lock' => $lock], ['id' => $id])->execute();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败，请重试']);
            }
        }
    }

    //-----------------------------------------------------------------仓库报表start

    /**仓库列表
     * @return string
     */
    public function actionRepo()
    {
        $p = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;

        $where['name']          = yii::$app->request->get('name');
        $where['begin_date']    = yii::$app->request->get('begin_date');
        $where['end_date']      = yii::$app->request->get('end_date');
        $where['customer_name'] = yii::$app->request->get('customer_name');
        $where['num']           = yii::$app->request->get('num');
        $where['invoice_order'] = trim(yii::$app->request->get('invoice_order'));
        $where['product']       = yii::$app->request->get('product');
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['name'] = $this->user['job_number'];
        }
        $repo_model   = new Repo();
        $repo_list    = $repo_model->get_repo_list($p, $s, $where);
        $repo_size    = $repo_model->get_repo_size($where);
        $repo_list    = $this->validateRepoCustomer($repo_list);
        $page         = $repo_size ? (ceil($repo_size / $s)) : 1;
        $staff_model  = new Staff();
        $saleman_list = $staff_model->get_all_saleman();
        $base_url     = '/table/repo' . $this->get_base_url();
        //仓库审核
        $model                          = new RepoFeeVerify();
        $verifyList                     = $model->all(['is_delete' => 1], false, false, ['date' => SORT_DESC]);
        yii::$app->view->params['page'] = ['page' => $page, 'curr' => $p, 'base_url' => $base_url, 'count' => $repo_size];
        return $this->render('repo', ['verifyList' => $verifyList, 'list' => $repo_list, 'staff' => $saleman_list]);
    }

    public function actionRepoBase()
    {
        $staff_model  = new Staff();
        $saleman_list = $staff_model->get_all_saleman();
        return json_encode(['staff' => $saleman_list]);
    }

    public function actionRepoList()
    {
        $p = yii::$app->request->get('p') ? yii::$app->request->get('p') : 1;
        $s = yii::$app->request->get('s') ? yii::$app->request->get('s') : 15;

        $where['name']          = yii::$app->request->get('name');
        $where['begin_date']    = yii::$app->request->get('beginTime');
        $where['end_date']      = yii::$app->request->get('endTime');
        $where['customer_name'] = yii::$app->request->get('customerName');
        $where['num']           = yii::$app->request->get('num');
        $where['invoice_order'] = trim(yii::$app->request->get('invoice'));
        $where['product']       = yii::$app->request->get('product');
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['name'] = $this->user['job_number'];
        }
        $repo_model = new Repo();
        $repo_list  = $repo_model->get_repo_list($p, $s, $where);
        $repo_list  = $this->validateRepoCustomer($repo_list);
        $size       = $repo_model->get_repo_size($where);

        return json_encode(['list' => $repo_list, 'total' => $size]);
    }

    public function validateRepoCustomer($repo_list)
    {
        $arr           = array_column($repo_list, 'num');
        $customerModel = new Customer();
        $customerList  = $customerModel->getCustomerByNum($arr);
        foreach ($repo_list as $k => $v) {
            if (
                isset($customerList[$v['num']]) &&
                $customerList[$v['num']] == $v['customer_name']
            ) {
                $repo_list[$k]['same'] = true;
            } else {
                $repo_list[$k]['same'] = false;
            }
        }
        return $repo_list;
    }

    /**仓库更新记录
     * @throws yii\db\Exception
     */
    public function actionRepo_edit_by_column()
    {
        $id     = yii::$app->request->post('id');
        $column = yii::$app->request->post('column');
        $value  = yii::$app->request->post('v');
        if (!is_numeric($id)) {
            return json_encode(['code' => 0, 'msg' => '数据错误']);
        }

        $model = new Repo();
        $info  = $model->one(['id' => $id]);
        if ($info['lock_status'] == 1) {
            return json_encode(['code' => 0, 'msg' => '当前记录已经锁定，无法修改']);
        }
        //要修改的是invoice，校验invoice是未结算的
        if ($column == 'invoice_order' && $value) {
            if ($this->orderService->isJiesuan(['invoice' => $value])) {
                return json_encode(['code' => 0, 'msg' => '该invoice已经结算,无法修改']);
            }
        }
        $data                     = [];
        $data[$column]            = $value;
        $data['last_modify']      = $this->user['job_number'];
        $data['last_modify_time'] = time();
        $re                       = $model->save($data, ['id' => $id]);
        //校验拆分项和主项费用是否相同
        $info = $model->one(['id' => $id]);
        $this->checkRepoFee($info['pid']);
        if ($re) {
            $output = ['code' => 1, 'msg' => '更新成功'];
        } else {
            $output = ['code' => 1, 'msg' => '更新失败,请重试'];
        }
        echo json_encode($output);

    }

    protected function checkRepoFee($pid)
    {
        $model = new Repo();
        $list  = $model->all(['pid' => $pid]);
        $sum1  = $sum2  = 0;
        foreach ($list as $v) {
            if ($v['pid'] == $v['id']) {
                $sum1 += $v['pay_all'];
            } else {
                $sum2 += $v['pay_all'];
            }
        }
        if ($sum2 == 0 || (round($sum1, 2) == round($sum2, 2))) {
            $same = true;
        } else {
            $same = false;
        }
        $model->save(['moneySame' => $same], ['pid' => $pid]);
    }

    /**
     *仓库拆分记录
     *
     */
    public function actionRepoSplit()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $model = new Repo();
            //检查是否拆分项
            $info = $model->one(['id' => $id]);
            if ($info['pid'] != $info['id']) {
                return json_encode(['code' => 0, 'msg' => '当前记录不是拆分项']);
            }
            //订单是否锁定
            if ($info['lock_status'] == 1) {
                return json_encode(['code' => 0, 'msg' => '当前记录已经锁定，无法修改']);
            }

            //复制一条记录

            $data = $model->one(['id' => $id]);
            unset($data['id']);
            $data['pid'] = $id;
            if ($model->insert($data)) {
                //校验金额是否一致
                $this->checkRepoFee($data['pid']);
                echo json_encode(['code' => 1, 'msg' => '拆分成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '拆分失败,请重试']);
            }
        }
    }

    /**锁定仓库
     * @throws yii\db\Exception
     */
    public function actionLockRepo()
    {
        if (yii::$app->request->isPost) {
            $id           = yii::$app->request->post('id');
            $param        = yii::$app->request->post('param');
            $value        = yii::$app->request->post('value');
            $data         = [];
            $data[$param] = $value;
            $model        = new Repo();
            $re           = $model->save($data, ['id' => $id]);
            if ($re) {
                $output = ['code' => 1, 'msg' => '更新成功'];
            } else {
                $output = ['code' => 1, 'msg' => '更新失败,请重试'];
            }
            echo json_encode($output);
        }
    }

    /**删除记录
     * @throws yii\db\Exception
     */
    public function actionDel_repo_by_id()
    {
        $id = yii::$app->request->post('id');
        if (!is_numeric($id)) {
            return json_encode(['code' => 0, 'msg' => '数据格式错误']);
        }
        $model = new Repo();
        $info  = $model->one(['id' => $id]);
        //未锁定才能修改
        if ($info['lock_status'] == 1) {
            return json_encode(['code' => 0, 'msg' => '记录已经锁定无法修改']);
        }
        $list = $model->all(['pid' => $id]);
        if (count($list) > 1) {
            return json_encode(['code' => 0, 'msg' => '请先删除子项']);
        }

        $re = $model->delete(['id' => $id]);
        if ($re) {
            $this->checkRepoFee($info['pid']);
            return json_encode(['code' => 1, 'msg' => '删除成功']);
        } else {
            return json_encode(['code' => 0, 'msg' => '删除失败,请重试']);
        }

    }

    /**
     * 订单汇总
     */
    public function actionOrder()
    {

        $p                           = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                           = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 50;
        $where['job_number']         = yii::$app->request->get('job_number');
        $where['customer_name']      = yii::$app->request->get('customer_name');
        $where['invoice']            = yii::$app->request->get('invoice');
        $where['begin_date']         = yii::$app->request->get('begin_date');
        $where['end_date']           = yii::$app->request->get('end_date');
        $where['confirm_begin_date'] = yii::$app->request->get('confirm_begin_date');
        $where['confirm_end_date']   = yii::$app->request->get('confirm_end_date');
        $where['invoice_status']     = yii::$app->request->get('invoice_status');
        $where['order_status']       = yii::$app->request->get('order_status');
        $where['purchase']           = yii::$app->request->get('purchase');
        $where['recommend']          = yii::$app->request->get('recommend');
        $where['is_jiesuan']         = yii::$app->request->get('is_jiesuan');
        $db                          = new Invoice();

        //业务员查看
        if ($this->user['role'] == 3) {
            $where['job_number'] = $this->user['job_number'];
        } elseif ($this->user['role'] == 4) {
            $where['purchase'] = $this->user['job_number'];
        }
        $list = $db->get_invoice_all_info($p, $s, $where);
        $size = $db->get_invoice_new_size($where);

        //读取已结算lock数据
        $jiesuanArr = [];
        foreach ($list['list'] as $v) {
            if ($v['is_jiesuan'] == 3) {
                $jiesuanArr[] = $v['id'];
            }
        }

        $invoiceLockmodel = new InvoiceLock();
        $jiesuanData      = $invoiceLockmodel->all(['invoice_id' => $jiesuanArr]);

        $page = $size ? ceil($size['num'] / $s) : 1;

        yii::$app->view->params['pagecount'] = isset($size['num']) ? $size['num'] : 0;
        $totalOrderPay                       = 0;
        $totalIncome                         = 0;
        $totalPay                            = 0;
        $totalFee                            = 0;
        $totalShip                           = 0;
        $totalPrint                          = 0;
        $totalRepo                           = 0;
        $totalBank                           = 0;
        $totalInland                         = 0;
        $totalOthers                         = 0;
        $totalProfit                         = 0;
        $totalSaleman                        = 0;
        $totalPurchase                       = 0;
        //给invoice添加收入
        $invoice_arr = [];
        foreach ($list['list'] as $k => $v) {
            $invoice_arr[] = $v['invoice'];
            foreach ($list['income'] as $k2 => $v2) {
                if (trim($v['invoice']) == trim($v2['invocie_num'])) {
                    $totalOrderPay += $v['order_pay'];
                    $totalIncome += $v2['in_come'];
                    $totalPay += $v2['total_fee'];
                    $totalFee += $v2['fee'];
                    $list['list'][$k]['income'] = $v2;
                    $list['list'][$k]['date2']  = $v2['date'];
                    unset($list['income'][$k2]);
                    break;
                }
            }
        }
        unset($list['income']);
        //invoice添加运费
        $express_model = new \app\models\Express();
        $express_list  = $express_model->get_all_express_money($invoice_arr);

        //invoice添加仓库费用
        $repo_model   = new \app\models\Repo();
        $repofee_list = $repo_model->get_repo_fee_by_invoice($invoice_arr);

        //打印费用添加
        $print_model = new \app\models\PrintModel();
        $print_list  = $print_model->get_print_fee_by_invoice($invoice_arr);

        //大货报销支出
        $bank_bill = new \app\models\Bank_bill();
        $bank_list = $bank_bill->get_money_by_invoice($invoice_arr);

        $othersList = $bank_bill->get_others_by_invoice($invoice_arr);

        //添加汇率
        $commonModel   = new \app\models\CommonModel();
        $exchange_list = json_decode($commonModel->get_all_exchange_rate(), true);

        //内陆费用添加
        $inlandModel = new \app\models\Inland();
        $inland_list = $inlandModel->get_inland_list_by_invoice($invoice_arr);

        //报销费用添加
        $baoxiaoModel = new Baoxiao();
        $baoxiaoList  = $baoxiaoModel->getBaoxiaoByInvoice($invoice_arr);
        foreach ($list['list'] as $k => $v) {
            $list['list'][$k]['express_fee'] = 0;
            foreach ($express_list as $v2) {
                if ($v['invoice'] == $v2['invoice_order']) {
                    if ($v['customer_num'] != $v2['customer_number']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['express_fee'] += $v2['fee'];
                    $totalShip += $v2['fee'];
                }
            }

            $list['list'][$k]['repo_fee'] = 0;
            foreach ($repofee_list as $v2) {
                if ($v['invoice'] == $v2['invoice_order']) {
                    if ($v['customer_num'] != $v2['num']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['repo_fee'] = $v2['pay_all'];
                    $totalRepo += $v2['pay_all'];
                    break;
                }
            }

            $list['list'][$k]['print_fee'] = 0;
            foreach ($print_list as $v2) {
                if ($v['invoice'] == $v2['invoice_order']) {
                    $list['list'][$k]['print_fee'] = $v2['fee'];
                    $totalPrint += $v2['fee'];
                    break;
                }
            }

            $list['list'][$k]['bank'] = 0;
            foreach ($bank_list as $v2) {
                if ($v['invoice'] == $v2['invocie_num']) {
                    if ($v['customer_num'] != $v2['number']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['bank'] = $v2['in_money'] - $v2['out_money'];
                    $totalBank += $v2['in_money'] - $v2['out_money'];
                    break;
                }
            }

            $list['list'][$k]['others'] = 0;
            foreach ($othersList as $v2) {
                if ($v['invoice'] == $v2['invocie_num']) {
                    $list['list'][$k]['others'] = $v2['in_money'] - $v2['out_money'];
                    $totalOthers += $v2['in_money'] - $v2['out_money'];
                    break;
                }
            }

            $list['list'][$k]['exchange_rate'] = 6.5;
            foreach ($exchange_list as $v2) {
                $date = isset($v['date2']) ? $v['date2'] : $v['date'];
                if (date('Ym', strtotime($date)) == $v2['month']) {
                    $list['list'][$k]['exchange_rate'] = $v2['rate'];
                    break;
                }
            }

            $list['list'][$k]['inland_fee'] = 0;
            foreach ($inland_list as $v2) {
                if ($v['invoice'] == $v2['invoice']) {
                    if ($v['customer_num'] != $v2['customer_num']) {
                        $list['list'][$k]['isSame'] = false;
                    }
                    $list['list'][$k]['inland_fee'] = $v2['total_fee'];
                    $totalInland += $v2['total_fee'];
                    break;
                }
            }
            $list['list'][$k]['baoxiao'] = isset($baoxiaoList[$v['invoice']]) ? $baoxiaoList[$v['invoice']] : 0;

        }

        $model      = new \app\models\Staff();
        $staff_list = $model->get_all_saleman();
        foreach ($list['list'] as $k => $v) {
            if (isset($v['income'])) {
                $clean = $v['income']['in_come'] + $v['income']['total_fee'] + $v['income']['fee'];
            } else {
                $clean = 0;
            }
            $list['list'][$k]['clean'] = $clean;
            $lirun                     = $clean > 0 ? round(($clean * $v['exchange_rate'] + $v['bank'] + $v['others'] - $v['express_fee'] - $v['print_fee'] - $v['repo_fee'] - $v['inland_fee'] - $v['baoxiao']), 2) : 0;
            $list['list'][$k]['lirun'] = $lirun;
            $totalProfit += $lirun;
            $tmp = BaseFunction::profit($v, $lirun, $staff_list);
            $totalSaleman += $tmp[0];
            $totalPurchase += $tmp[1];
            $list['list'][$k]['saleman_get']  = $tmp[0];
            $list['list'][$k]['purchase_get'] = $tmp[1];
            if ($v['rate_status'] == 1) {
                $list['list'][$k]['saleman_get'] = round($lirun * $v['rale_rate'] / 100, 2);
            }
        }

        //添加未录入invoice的invoice 和重复的invocie
        $invoiceNewModal = new Invoice_new();
        $notUseList      = $invoiceNewModal->notUseInvoice();
        $sameInovice     = $invoiceNewModal->getSameInvoice();

        $invoice_status                           = require ROOT_PATH . '/config/invoice_status.php';
        yii::$app->view->params['invoice_status'] = $invoice_status;
        $model                                    = new CustomerRefer();
        $referList                                = $model->list();

        $base_url = '/table/order' . $this->get_base_url();
        $total    = [
            'totalOrderPay' => $totalOrderPay,
            'totalIncome'   => $totalIncome,
            'totalPay'      => $totalPay,
            'totalFee'      => $totalFee,
            'totalShip'     => $totalShip,
            'totalPrint'    => $totalPrint,
            'totalRepo'     => $totalRepo,
            'totalBank'     => $totalBank,
            'totalInland'   => $totalInland,
            'totalOthers'   => $totalOthers,
            'totalProfit'   => $totalProfit,
            'totalSaleman'  => $totalSaleman,
            'totalPurchase' => $totalPurchase,
        ];
        yii::$app->view->params['sameInvoice'] = $sameInovice;
        yii::$app->view->params['referList']   = $referList;
        yii::$app->view->params['notUseList']  = $notUseList;
        yii::$app->view->params['staff_list']  = $staff_list;
        yii::$app->view->params['page']        = ['page' => $page, 'curr' => $p, 'base_url' => $base_url];
        foreach ($list['list'] as $k => $v) {
            foreach ($jiesuanData as $k2 => $v2) {
                if ($v['id'] == $v2['invoice_id']) {
                    $list['list'][$k]['children'] = $v2;
                }
            }
        }
        return $this->render('order', ['total' => $total, 'list' => $list, 'role' => $this->user['role']]);
    }

    /**订单汇总每条记录详情
     * @return string
     */
    public function actionOrder_detail()
    {
        $in = yii::$app->request->get('invoice');
        //invoice 产品添加
        $model        = new Product();
        $product_list = $model->get_invoice_product($in);

        $model  = new Invoice_new();
        $detail = $model->getDetailByInvoice($in);
        //获取in所有产品
        $model = new Bank_bill();
        $list  = $model->get_bank_info_by_in($in);
        //仓库费用添加
        $repo_model = new Repo();
        $repo_info  = $repo_model->get_repo_info_by_invoice($in);
        //印刷费添加
        $print_model = new PrintModel();
        $print_info  = $print_model->get_print_list_by_invoice($in);
        //内陆费
        $inland_model = new Inland();
        $inland_info  = $inland_model->get_inland_list_by_invoice((array) $in);

        $invoice_model = new Invoice_new();
        $info          = $invoice_model->get_invoice_info_by_invoice($in);

        //invoice 收入$添加
        $model       = new Income();
        $income_list = $model->get_income_by_invoice($in);

        $express_model = new Express();
        $express_list  = $express_model->get_all_express_money($in);

        $expressType = $express_model->get_express_type();

        //读取采购单合同信息
        $purchase      = new Purchase();
        $purchase_list = $purchase->all(['invoice' => $in]);
        $arr           = [];
        foreach ($purchase_list as $v) {
            $tmp = json_decode($v['product_list'], true);
            foreach ($tmp as $v2) {
                array_push($arr, $v2);
            }
        }
        //报销费用添加
        $baoxiaoModel         = new Baoxiao();
        $baoxiaoList          = $baoxiaoModel->getBaoxiaoByInvoice($in);
        $data                 = [];
        $data['baoxiao']      = $baoxiaoList;
        $data['edit']         = $detail['is_jiesuan'] == 3 ? false : true;
        $data['express_list'] = $express_list;
        $data['detail']       = $detail;
        $data['income_list']  = $income_list;
        $data['inland_info']  = $inland_info;
        $data['repo_info']    = $repo_info;
        $data['print_info']   = $print_info;
        $data['info']         = $info;
        $data['list']         = $list;
        $data['product']      = $product_list;
        return $this->render('order_detail', ['data' => $data, 'productList' => $arr, 'expressType' => $expressType]);
    }

    /**删除订单
     * @throws yii\db\Exception
     */
    public function actionDelOrderDetailRecord()
    {
        $id = yii::$app->request->post('id');
        $in = yii::$app->request->post('invoice');
        if (yii::$app->request->isPost) {
            if ($this->_checkOrderIsJieSuan($in)) {
                return json_encode(['code' => 0, 'msg' => '订单已结算,无法删除']);
            }
            $re = yii::$app->db->createCommand()->delete(yii::$app->db->tablePrefix . 'product', ['id' => $id])->execute();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '删除成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '删除失败,请重试']);
            }
        }
    }

    /**订单是否结算
     * @param $in
     */
    public function _checkOrderIsJieSuan($in)
    {
        $model  = new Invoice_new();
        $detail = $model->getDetailByInvoice($in);
        if ($detail['is_jiesuan'] == 3) {
            return true;
        } else {
            return false;
        }
    }

    public function actionUpdate_order_pay()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法请求']);
        }
        $id     = yii::$app->request->post('id');
        $value  = yii::$app->request->post('v', '');
        $column = yii::$app->request->post('column', '');
        $model  = new Invoice_new();
        $info   = $model->one(['id' => $id]);
        if ($info['is_jiesuan'] == 3 || ($value == 3 && $column == 'is_jiesuan')) {
            BaseFunction::check_edit_auth($this->user['role']);
            $this->generateLockData(['invoice' => $info['invoice']]);
        }
        $data[$column] = $value;
        $re            = $model->save($data, ['id' => $id]);
        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '修改成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '修改失败，请重试']);
        }
    }

    /**
     *生成订单锁定数据
     *
     */
    public function generateLockData($invoice)
    {
        //将订单修改为结算状态生成不可变数据
        $model       = new Invoice_new();
        $info        = $model->one(['invoice' => $invoice]);
        $data        = [];
        $invoice_arr = $invoice;
        //收款数据添加
        $model               = new Income();
        $list                = $model->all(['invocie_num' => $invoice]);
        $data['real_income'] = 0;
        foreach ($list as $v) {
            $data['real_income'] = $v['in_come'] + $v['total_fee'] + $v['fee'];
        }
        //invoice添加运费
        $express_model = new Express();
        $express_list  = $express_model->all(['invoice_order' => $invoice]);

        $data['express_fee'] = $express_list ? array_sum(array_column($express_list, 'fee')) : 0;
        //invoice添加仓库费用
        $repo_model   = new Repo();
        $repofee_list = $repo_model->all(['invoice_order' => $invoice]);

        $data['repo_fee'] = $repofee_list ? array_sum(array_column($repofee_list, 'pay_all')) : 0;

        //打印费用添加
        $print_model = new PrintModel();
        $print_list  = $print_model->all(['invoice_order' => $invoice]);

        $data['print_fee'] = $print_list ? array_sum(array_column($print_list, 'fee')) : 0;

        //大货报销支出
        $bank_bill           = new Bank_bill();
        $bank_list           = $bank_bill->get_money_by_invoice($invoice_arr);
        $data['product_fee'] = array_sum(array_column($bank_list, 'in_money')) - array_sum(array_column($bank_list, 'out_money'));
        $othersList          = $bank_bill->get_others_by_invoice($invoice_arr);
        $data['others']      = array_sum(array_column($othersList, 'in_money')) - array_sum(array_column($othersList, 'out_money'));
        //内陆费用添加
        $inlandModel        = new \app\models\Inland();
        $inland_list        = $inlandModel->all(['invoice' => $invoice]);
        $data['inland_fee'] = $inland_list ? array_sum(array_column($inland_list, 'total_fee')) : 0;
        //报销费用添加
        $baoxiaoModel      = new Baoxiao();
        $baoxiaoList       = $baoxiaoModel->getBaoxiaoByInvoice($invoice_arr);
        $data['reimburse'] = $baoxiaoList ? array_sum(array_column($baoxiaoList, 'fee')) : 0;

        $model              = new InvoiceLock();
        $data['invoice_id'] = $info['id'];
        if ($model->one(['invoice_id' => $info['id']])) {
            $model->save($data, ['invoice_id' => $info['id']]);
        } else {
            $model->insert($data);
        }
    }

    public function actionUpdateOrder()
    {
        if (yii::$app->request->isPost) {
            $invoice = yii::$app->request->post('invoice');
            $value   = yii::$app->request->post('value');
            $column  = yii::$app->request->post('param');

            $re = yii::$app->db->createCommand()
                ->update(yii::$app->db->tablePrefix . "invoice_new", [$column => $value], ['invoice' => $invoice])
                ->execute();
            //生成invoice
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败，请重试']);
            }
        } else {
            echo json_encode(['code' => 0, 'msg' => '非法请求']);
        }
    }

    protected function getInvoiceFee($in)
    {
        $model        = new Product();
        $product_list = $model->get_invoice_product($in);

        $model  = new Invoice_new();
        $detail = $model->getDetailByInvoice($in);
        //获取in所有产品
        $model = new Bank_bill();
        $list  = $model->get_bank_info_by_in($in);
        //仓库费用添加
        $repo_model = new Repo();
        $repo_info  = $repo_model->get_repo_info_by_invoice($in);
        //印刷费添加
        $print_model = new PrintModel();
        $print_info  = $print_model->get_print_list_by_invoice($in);
        //内陆费
        $inland_model = new Inland();
        $inland_info  = $inland_model->get_inland_list_by_invoice((array) $in);

        $invoice_model = new Invoice_new();
        $info          = $invoice_model->get_invoice_info_by_invoice($in);

        //invoice 收入$添加
        $model       = new Income();
        $income_list = $model->get_income_by_invoice($in);

        $express_model = new Express();
        $express_list  = $express_model->get_all_express_money($in);

        $expressType = $express_model->get_express_type();

        return [];
    }

    /**收款汇总页面
     * @return string
     */
    public function actionSellperformance()
    {
        $year  = yii::$app->request->get('year') ?? '2017';
        $total = [];
        $db    = new Income();
        $list  = $db->sell_performance($year);
        $arr   = [];
        foreach ($list as $k => $v) {
            $arr[$v['service_name']] = [];
        }
        foreach ($list as $k => $v) {
            if (isset($total[$v['MONTH']])) {
                $total[$v['MONTH']] += $v['money'];
            } else {
                $total[$v['MONTH']] = 0;
                $total[$v['MONTH']] += $v['money'];
            }
            $arr[$v['service_name']]['service_name']                      = $v['service_name'];
            $arr[$v['service_name']]['list'][$v['MONTH']][$v['pay_from']] = $v;
        }
        $model     = new Staff();
        $staffList = $model->get_all_saleman();

        if ($this->user['role'] != 1 && $this->user['role'] != 2 && $this->user['role'] != 14) {
            foreach ($arr as $k => $v) {
                if ($k != $this->user['job_number']) {
                    unset($arr[$k]);
                }
            }
        }
        $picture = [];
        foreach ($arr as $k => $v) {
            if ($v['service_name'] == 999 || $v['service_name'] == 207 || $v['service_name'] == 1003) {
                unset($arr[$k]);
                continue;
            }
            foreach ($staffList as $v2) {
                if ($k == $v2['job_number']) {
                    $arr[$k]['name']     = $v2['name'];
                    $picture[$k]['name'] = $v2['name'];
                }
            }
            $arr[$k]['list']['total'][1] = 0;
            $arr[$k]['list']['total'][2] = 0;
            $arr[$k]['list']['total'][3] = 0;
            $arr[$k]['list']['total'][4] = 0;
            foreach ($v['list'] as $v2) {
                foreach ($v2 as $v3) {
                    if (in_array($v3['pay_from'], [1, 2, 3, 4])) {
                        $arr[$k]['list']['total'][$v3['pay_from']] += $v3['money'];
                    }
                }
            }
            $picture[$k]['type'] = 'line';
            $picture[$k]['data'] = [];
            for ($i = 1; $i <= 12; $i++) {
                $money     = 0;
                $key       = $year . '-' . str_pad($i, 2, 0, STR_PAD_LEFT);
                $total[$k] = 0;
                if (isset($v['list'][$key])) {
                    foreach ($v['list'][$key] as $v2) {
                        $money += $v2['money'];
                    }
                }
                $picture[$k]['data'][] = $money;
            }
        }
        $data = [];
        foreach ($picture as $v) {
            $data[] = $v;
        }
        yii::$app->view->params['year']    = $year;
        yii::$app->view->params['total']   = $total;
        yii::$app->view->params['picture'] = $data;
        yii::$app->view->params['list']    = $arr;
        return $this->render('sellperformance');
    }

    public function actionPerformancedetail()
    {
        $id    = yii::$app->request->get('id');
        $month = yii::$app->request->get('month');
        if (is_numeric($id) && $month != 12) {
            $model                          = new \app\models\Income();
            $list                           = $model->get_list_by_service_and_month($id, $month);
            yii::$app->view->params['list'] = $list;
            return $this->render('performancedetail');
        } elseif (is_numeric($id) && $month == 12) {
            $model                          = new \app\models\Income();
            $list                           = $model->get_all_year_list_by_service($id);
            yii::$app->view->params['list'] = $list;
            return $this->render('performancedetail');
        }
    }

    public function actionSell_count()
    {
        $year  = yii::$app->request->get('year') ? yii::$app->request->get('year') : date('Y');
        $where = [];
        if ($this->user['role'] != 1 && $this->user["role"] != 2 && $this->user['role'] != 14) {
            $where['saleman_num'] = $this->user['job_number'];
        }
        $model = new Invoice_new();
        $list  = $model->getOrderPayByYear($year, $where);
        $arr   = [];
        $total = [];
        foreach ($list as $v) {
            $arr[$v['saleman_num']][$v['m']][] = $v;
            if (isset($total[$v['m']])) {
                $total[$v['m']]['money'] += $v['order_pay'];
                $total[$v['m']]['num']++;
            } else {
                $total[$v['m']]['money'] = $v['order_pay'];
                $total[$v['m']]['num']   = 1;
            }
        }
        $total['total']['money'] = round(array_sum(array_column($total, 'money')), 2);
        $total['total']['num']   = (int) array_sum(array_column($total, 'num'));
        $totalArr                = $total;
        foreach ($arr as $k => $v) {
            $total    = 0;
            $totalNum = 0;
            foreach ($v as $k2 => $vv) {
                $tmp = 0;
                $num = 0;
                foreach ($vv as $k3 => $vvv) {
                    $tmp += $vvv['order_pay'];
                    $num++;
                    $totalNum++;
                }
                $total += $tmp;
                $arr[$k][$k2]['total'] = round($tmp, 2);
                $arr[$k][$k2]['num']   = $num;
                $arr[$k]['name']       = $vvv['saleman'];
            }
            $arr[$k]['num']   = $totalNum;
            $arr[$k]['total'] = round($total, 2);
        }
//        echo \GuzzleHttp\json_encode($totalArr);
        //        exit;
        return $this->render('sell_count', ['total' => $totalArr, 'list' => $arr, 'year' => $year]);
    }

    public function actionSell_detail()
    {
        $id    = yii::$app->request->get('id');
        $m     = yii::$app->request->get('m');
        $model = new \app\models\Invoice();
        $list  = $model->get_invoice_new_by_id($id, $m);
        foreach ($list['list'] as $k => $v) {
            foreach ($list['income'] as $k2 => $v2) {
                if ($v['invoice'] == $v2['invocie_num']) {
                    $list['list'][$k]['income'] = $v2;
                    unset($list['income'][$k2]);
                    break;
                }
            }
        }
        unset($list['income']);
        //统计数据
        $all_income = 0;
        $all_clean  = 0;
        foreach ($list['list'] as $k => $v) {
            if (isset($v['income'])) {
                $all_income += $v['income']['in_come'];
                $all_clean += $v['income']['in_come'] + $v['income']['total_fee'] + $v['income']['fee'];
            }
        }

        yii::$app->view->params['all_income'] = $all_income;
        yii::$app->view->params['all_clean']  = $all_clean;
        yii::$app->view->params['list']       = $list;
        return $this->render('sell_detail');
    }

    //询盘汇总
    public function actionInquiry()
    {
        $date = yii::$app->request->get('date');
        if ($date) {
            $month = date('Y-m', strtotime($date));
        } else {
            $month = date('Y-m');
        }
        $year       = date('Y', strtotime($month));
        $model      = new Inquiry();
        $list       = $model->get_inquiery_by_month($month);
        $month_list = $model->get_inquiry_by_month_service_name($year);
        if ($this->user['role'] == 3) {
            foreach ($month_list as $k => $v) {
                if ($k != $this->user['zh_name']) {
                    unset($month_list[$k]);
                }
            }
        } else {
            yii::$app->view->params['list'] = $list;
        }
        //图表信息
        $chartData = $model->inquiryGroupByYear();
        $title     = [];
        $tmp       = [];
        foreach ($chartData as $k => $v) {
            $key = 0;
            foreach ($v as $k2 => $v2) {
                if (date('Y', strtotime($v2['month'])) != $year) {
                    unset($chartData[$k][$k2]);
                } else {
                    $tmp[$k][$key]['name']  = $v2['month'];
                    $tmp[$k][$key]['value'] = $v2['num'];
                    $title[]                = $v2['month'];
                    $key++;
                }
            }
        }
        // echo json_encode($chartData);exit;
        yii::$app->view->params['title']      = $title;
        yii::$app->view->params['chartData']  = $tmp;
        yii::$app->view->params['year']       = $year;
        yii::$app->view->params['month_list'] = $month_list;

        return $this->render('inquiry');
    }

    //样品费
    public function actionSample_fee()
    {
        $p                      = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                      = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where                  = [];
        $where['number']        = yii::$app->request->get('number');
        $where['service_name']  = yii::$app->request->get('service_name');
        $where['customer_name'] = yii::$app->request->get('customer_name');
        $model                  = new Income();
        $staff_model            = new Staff();
        $list                   = $model->sample_fee_list($p, $s, $where);
        //获取客户样品费用
        $customer_num = [];
        foreach ($list as $value) {
            $customer_num[] = $value['number'];
        }
        //快递样品费
        $expressModel = new Express();
        $expressList  = $expressModel->getSampleFee($customer_num);
        $bank_model   = new Bank_bill();
        $bank_list    = $bank_model->get_shopping($customer_num);
        $staff_list   = $staff_model->get_all_saleman();
        foreach ($list as $k => $v) {
            if (isset($bank_list[$v['number']])) {
                $list[$k]['bank'] = $bank_list[$v['number']];
            };
            foreach ($staff_list as $k2 => $v2) {
                if ($v['service_name'] == $v2['job_number']) {
                    $list[$k]['zh_name'] = $v2['name'];
                }
            }
            foreach ($expressList as $k2 => $v2) {
                if ($v['number'] == $v2['customer_number']) {
                    $list[$k]['ship'] = $v2['fee'];
                }
            }
        }
        $size                           = $model->sample_fee_size($where);
        $page                           = $size ? ceil($size / $s) : 1;
        $base_url                       = '/table/sample_fee' . $this->get_base_url();
        yii::$app->view->params['page'] = [
            'page' => $page, 'curr' => $p, 'base_url' => $base_url, 'total' => $size,
        ];
        yii::$app->view->params['list']       = $list;
        yii::$app->view->params['staff_list'] = $staff_list;
        return $this->render('sample_fee');
    }

    /**
     * 生成产品
     */
    public function actionGenerateProduct()
    {
        $in = yii::$app->request->post('in');
        //判断是否已结算
        $model  = new Invoice_new();
        $detail = $model->getDetailByInvoice($in);
        if ($detail['is_jiesuan'] == 3) {
            echo json_encode(['code' => 0, 'msg' => '订单已结算，无法修改']);
            exit;
        }
        $model        = new Product();
        $invoiceModel = new Invoice();
        $info         = $invoiceModel->getRecordByParam(['param' => 'invoice_id', 'value' => $in]);

        if ($info) {
            $model->deleteRecordByInvoice($in);
            $data = json_decode($info['product_list'], true);
            foreach ($data as $v) {
                $tmp                       = [];
                $tmp['invoice']            = $info['invoice_id'];
                $tmp['price_dollar']       = $v['price'] ? $v['price'] : 0;
                $tmp['number']             = $v['pcs'];
                $tmp['customer_extra_fee'] = $v['extra_fee'];
                $tmp['product_name_en']    = $v['item'];
                $model->insertRecord($tmp);
            }
            $model->get_invoice_product($in);
            //服务费，海运费添加
            $service                = json_decode($info['service'], true);
            $tmp                    = [];
            $tmp['invoice']         = $info['invoice_id'];
            $tmp['price_dollar']    = $service['fee'] ? $service['fee'] : 0;
            $tmp['product_name']    = '服务费';
            $tmp['product_name_en'] = 'service fee';
            $model->insertRecord($tmp);

            $service                = json_decode($info['ship'], true);
            $tmp                    = [];
            $tmp['invoice']         = $info['invoice_id'];
            $tmp['price_dollar']    = $service['fee'] ? $service['fee'] : 0;
            $tmp['product_name']    = '运费';
            $tmp['product_name_en'] = 'shipping fee';
            $model->insertRecord($tmp);
            $duty                   = json_decode($info['duty'], true);
            $tmp                    = [];
            $tmp['invoice']         = $info['invoice_id'];
            $tmp['price_dollar']    = $duty['show'] ? $duty['fee'] : 0;
            $tmp['product_name']    = '关税费用';
            $tmp['product_name_en'] = 'import duty';
            $model->insertRecord($tmp);

            //其他费用信息印刷费添加
            $printModel = new PrintModel();
            $list       = $printModel->all(['invoice_order' => $in]);
            $sum        = 0;
            foreach ($list as $v) {
                $sum += $v['fee'];
            }
            $arr = [["印刷费", $sum]];
            //仓库费添加
            $repoModel = new Repo();
            $list      = $repoModel->all(['invoice_order' => $in]);
            $sum       = 0;
            foreach ($list as $v) {
                $sum += $v['pay_all'];
            }
            array_push($arr, ["仓库费", $sum]);
            //内陆费添加
            $inlandModel = new Inland();
            $list        = $inlandModel->all(['invoice' => $in]);
            $sum         = 0;
            foreach ($list as $v) {
                $sum += $v['total_fee'];
            }
            array_push($arr, ["内陆费", $sum]);
            //报销费添加
            $baoxiao = new Baoxiao();
            $list    = $baoxiao->all(['invoice' => $in]);
            $sum     = 0;
            foreach ($list as $v) {
                $sum += $v['fee'];
            }
            array_push($arr, ["报销费", $sum]);
            array_push($arr, ['退税', 0]);
            array_push($arr, ['其他', 0]);

            foreach ($arr as $v) {
                $tmp                 = [];
                $tmp['price_rmb']    = $v[1];
                $tmp['product_name'] = $v[0];
                $tmp['invoice']      = $info['invoice_id'];
                $model->insertRecord($tmp);
            }
            echo json_encode(['code' => 1, 'msg' => '生成成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '当前记录未生成invoice,请先生成invoice']);
        }
    }

    //支出每月占比
    public function actionMonth_pay()
    {
        $year      = yii::$app->request->get('year') ? yii::$app->request->get('year') : date('Y');
        $model     = new Bank_bill();
        $bank_type = $model->get_bank_type();
        foreach ($bank_type as $k => $v) {
            if ($v['id'] == 8) {
                unset($bank_type[$k]);
            }
        }
        $list = $model->month_pay($year);
        foreach ($list as $k => $v) {
            if ($v['id'] == 8) {
                unset($list[$k]);
            }
        }
        $arr   = [];
        $total = [];
        foreach ($list as $v) {
            if (isset($total[$v['id']])) {
                $total[$v['id']]['in_money'] += $v['in_money'];
                $total[$v['id']]['out_money'] += $v['out_money'];
            } else {
                $total[$v['id']]['in_money']  = $v['in_money'];
                $total[$v['id']]['out_money'] = $v['out_money'];
            }
            if (isset($total['total'])) {
                $total['total'] += ($v['out_money'] - $v['in_money']);
            } else {
                $total['total'] = $v['out_money'] - $v['in_money'];
            }
            $arr[$v['date']]['data'][$v['id']] = $v;
        }
        foreach ($arr as $k => $v) {
            foreach ($v['data'] as $k2 => $v2) {
                if (!isset($arr[$k]['data']['total'])) {
                    $arr[$k]['data']['total'] = $v2['out_money'] - $v2['in_money'];
                } else {
                    $arr[$k]['data']['total'] += ($v2['out_money'] - $v2['in_money']);
                }
            }
        }
        yii::$app->view->params['total']     = $total;
        yii::$app->view->params['bank_type'] = $bank_type;
        yii::$app->view->params['list']      = $arr;
        return $this->render('month_pay');
    }

    /**内陆费列表
     * @return string
     */
    public function actionInland()
    {
        $p                      = is_numeric(yii::$app->request->get('page')) ? yii::$app->request->get('page') : 1;
        $s                      = is_numeric(yii::$app->request->get('per-page')) ? yii::$app->request->get('per-page') : 15;
        $where                  = [];
        $where['saleman']       = yii::$app->request->get('saleman');
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['customer_num']  = trim(yii::$app->request->get('customer_num'));
        $where['invoice']       = trim(yii::$app->request->get('invoice'));
        $where['order_num']     = trim(yii::$app->request->get('order_num'));
        $where['proxy_company'] = trim(yii::$app->request->get('proxy_company'));
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['saleman'] = $this->user['job_number'];
        }
        $service                                      = new InlandService();
        $list                                         = $service->list($p, $s, $where);
        $size                                         = $service->size($where);
        $list                                         = $service->validateCustomer($list);
        $staffModel                                   = new Staff();
        $staff_list                                   = $staffModel->get_all_saleman();
        $model_factory                                = new ModelFactory();
        $page                                         = new Pagination(['totalCount' => $size, 'pageSize' => $s]);
        $proxy_company_list                           = $model_factory->get_proxy_company()->get_proxy_company();
        yii::$app->view->params['proxy_company_list'] = $proxy_company_list;
        yii::$app->view->params['staff_list']         = $staff_list;
        yii::$app->view->params['list']               = $list;
        return $this->render('/finance/inland', ['page' => $page]);
    }

    public function actionInlandList()
    {
        $p                      = is_numeric(yii::$app->request->get('page')) ? yii::$app->request->get('page') : 1;
        $s                      = is_numeric(yii::$app->request->get('per-page')) ? yii::$app->request->get('per-page') : 15;
        $where                  = [];
        $where['saleman']       = yii::$app->request->get('saleman');
        $where['customer_name'] = trim(yii::$app->request->get('customer_name'));
        $where['customer_num']  = trim(yii::$app->request->get('customer_num'));
        $where['invoice']       = trim(yii::$app->request->get('invoice'));
        $where['order_num']     = trim(yii::$app->request->get('order_num'));
        $where['proxy_company'] = trim(yii::$app->request->get('proxy_company'));
        if ($this->user['role'] != 1 && $this->user['role'] != 2) {
            $where['saleman'] = $this->user['job_number'];
        }
        $service = new InlandService();
        $list    = $service->list($p, $s, $where);
        $size    = $service->size($where);
        $list    = $service->validateCustomer($list);
        return json_encode(['list' => $list, 'total' => $size]);
    }

    public function actionInlandBase()
    {
        $staffModel         = new Staff();
        $staff_list         = $staffModel->get_all_saleman();
        $model_factory      = new ModelFactory();
        $proxy_company_list = $model_factory->get_proxy_company()->get_proxy_company();
        return json_encode(['staff' => $staff_list, 'proxy_company' => $proxy_company_list]);
    }

    /**内陆费删除
     * @throws yii\db\Exception
     */
    public function actionInlandDel()
    {
        $id = yii::$app->request->post('id');
        BaseFunction::check_edit_auth($this->user['role']);
        $model = new Inland();
        $info  = $model->one(['id' => $id]);
        if ($info['lock_status'] == 1) {
            return json_encode(['code' => 0, 'msg' => '当前记录已经锁定']);
        }
        $list = $model->all(['pid' => $id]);
        if ($list && count($list) > 1) {
            return json_encode(['code' => 0, 'msg' => '请先删除子项']);
        }
        $re = $model->delete(['id' => $id]);
        if ($re) {
            echo json_encode(['code' => 1, 'msg' => '删除成功']);
        } else {
            echo json_encode(['code' => 0, 'msg' => '删除失败，请重试']);
        }
    }

    /**拆分内陆费
     * @throws yii\db\Exception
     */
    public function actionSplitInland()
    {
        if (yii::$app->request->isPost) {
            $id = yii::$app->request->post('id');
            //复制一条记录
            $model = new Inland();
            $list  = $model->one(['id' => $id]);
            if ($list['lock_status'] == 1) {
                return json_encode(['code' => 0, 'msg' => '订单数据已经锁定']);
            }
            $list['pid'] = $id;
            unset($list['id']);
            $re = $model->insert($list);
            //校验金额一致
            $service = new InlandService();
            $service->checkMoneySame($id);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => '添加失败', 'msg' => '请重试']);
            }
        }
    }

    /**
     *内陆费数据更新
     *
     */
    public function actionUpdate_inland()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $model = new Inland();
            $info  = $model->one(['id' => $id]);
            if ($info['lock_status'] == 1) {
                return json_encode(['code' => 0, 'msg' => '记录已被锁定无法修改']);
            }
            $data   = [];
            $column = yii::$app->request->post('column');
            $value  = yii::$app->request->post('value');

            //更新数据为invoice判断invoice是否结算
            if ($column == 'invoice' && $value) {
                if ($this->orderService->isJiesuan(['invoice' => $value])) {
                    return json_encode(['code' => 0, 'msg' => '当前invoice已经结算']);
                }
            }
            $data[$column]            = $value;
            $data['last_modify']      = $this->user['job_number'];
            $data['last_modify_time'] = time();
            $re                       = $model->save($data, ['id' => $id]);
            if ($re) {
                $service = new InlandService();
                $service->checkMoneySame($info['pid']);
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
            }
        }
    }

    public function actionLockInland()
    {
        BaseFunction::check_edit_auth($this->user['role']);
        if (yii::$app->request->isPost) {
            $id                       = yii::$app->request->post('id');
            $data                     = [];
            $column                   = yii::$app->request->post('param');
            $value                    = yii::$app->request->post('value');
            $data[$column]            = $value;
            $data['last_modify']      = $this->user['job_number'];
            $data['last_modify_time'] = time();
            $model                    = new Inland();
            $re                       = $model->save($data, ['id' => $id]);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
            }
        }
    }

    public function actionFinance()
    {
        $m          = yii::$app->request->get('m') ? yii::$app->request->get('m') : date('Y-m');
        $type       = (int) yii::$app->request->get('type') ? (int) yii::$app->request->get('type') : 4;
        $model      = new Staff();
        $staff_list = $model->get_all_saleman();
        if ($type == 1) {
            yii::$app->view->params['table'] = 'finance_part1';

            $model        = new ModelFactory();
            $bankModel    = $model->bank();
            $incomeModel  = $model->loadmodel('\app\models\Income');
            $exchaneModel = $model->loadModel('\app\models\CommonModel');
            $rate_list    = json_decode($exchaneModel->get_all_exchange_rate(), true);

            $rate_list['curr'] = [
                'month'        => date('Ym'),
                'rate'         => yii::$app->params['exchange_rate'],
                'account_rate' => yii::$app->params['exchange_rate'],
            ];
            //获取所有收入
            $type         = [8];
            $all_income   = [];
            $month_income = $incomeModel->get_sum_income_by_month($m);
            $list         = $incomeModel->get_sum_income_by_year($m);

            $month_sum = $month_income['income'] * (yii::$app->params['exchange_rate']);
            $year_sum  = 0;
            foreach ($rate_list as $v) {
                if ($v['month'] == date('Ym', strtotime($m))) {
                    $month_sum = $v['account_rate'] * $month_income['income'];
                }
                foreach ($list as $k => $v2) {
                    if ($v['month'] == date('Ym', strtotime($k))) {
                        $year_sum += $v2['income'] * $v['account_rate'];
                    }
                }
            }
            $all_income['month']['income'] = $month_sum;
            $all_income['year']['income']  = $year_sum;
            //订单产品成本 --大货类型
            $type        = [1, 2, 11, 28];
            $product_pay = $bankModel->get_info_by_type($type, $m);

            //订单货运成本
            $type        = [3, 10, 20];
            $express_pay = $bankModel->get_info_by_type($type, $m);

            //费用支出
            $type    = [4, 19, 12, 13, 14, 15];
            $fee_pay = $bankModel->get_info_by_type($type, $m);

            //退税款
            $type    = [22];
            $tax_pay = $bankModel->get_info_by_type($type, $m);

            //营业费用
            $type         = [5, 16];
            $business_pay = $bankModel->get_info_by_type($type, $m);

            //管理费用
            $type       = [6, 7, 18, 25];
            $manage_pay = $bankModel->get_info_by_type($type, $m);

            //财务费用
            $type        = [26];
            $finance_pay = $bankModel->get_info_by_type($type, $m);
            //营业外收入
            $type          = [21];
            $others_income = $bankModel->get_info_by_type($type, $m);
            //营业外支出
            $type       = [9, 17];
            $others_pay = $bankModel->get_info_by_type($type, $m);

            yii::$app->view->params['info'] = [
                'all_income'    => $all_income,
                'product_pay'   => $product_pay,
                'express_pay'   => $express_pay,
                'fee_pay'       => $fee_pay,
                'tax_pay'       => $tax_pay,
                'business_pay'  => $business_pay,
                'manage_pay'    => $manage_pay,
                'finance_pay'   => $finance_pay,
                'others_income' => $others_income,
                'others_pay'    => $others_pay,

            ];
        } elseif ($type == 2) {
        } elseif ($type == 3) {
            $model                           = new ModelFactory();
            $bankModel                       = $model->bank();
            $list                            = $bankModel->bank_remain($m);
            yii::$app->view->params['m']     = $m;
            yii::$app->view->params['list']  = $list;
            yii::$app->view->params['table'] = 'finance_part3';
        } elseif ($type == 4) {
            //月度应收表
            $model                          = new CommonModel();
            $exchange                       = json_decode($model->get_all_exchange_rate(), true);
            $month                          = date('Ym', strtotime($m));
            yii::$app->view->params['rate'] = 6.8;
            foreach ($exchange as $v) {
                if ($v['month'] == $month) {
                    yii::$app->view->params['rate'] = $v['rate'];
                    break;
                }
            }
            $model                           = new FinanceService();
            $list                            = $model->month_income($m);
            yii::$app->view->params['list']  = $list;
            yii::$app->view->params['table'] = 'finance_part4';
        } elseif ($type == 5) {
            //月度应付表
            $where            = [];
            $where['saleman'] = yii::$app->request->get('saleman');
            $where['m']       = date('ym', strtotime($m));
            $model            = new ModelFactory();
            $modelStaff       = $model->staff();
            $staff_list       = $modelStaff->get_all_saleman();
            $service          = new FinanceService();
            $list             = $service->month_pay($where);
            $total_need_pay   = 0;
            $total_have_pay   = 0;
            foreach ($list as $k => $v) {
                $total_need_pay += $v['need_pay'];
                $total_have_pay += $v['have_pay'];
                foreach ($staff_list as $v2) {
                    if ($v['purchase'] == $v2['job_number']) {
                        $list[$k]['name'] = $v2['name'];
                        break;
                    }
                }
            }
            yii::$app->view->params['staff_list'] = $staff_list;
            yii::$app->view->params['total']      = ['total_need_pay' => $total_need_pay, 'total_have_pay' => $total_have_pay];
            yii::$app->view->params['list']       = $list;
            yii::$app->view->params['table']      = 'finance_part5';
        }
        return $this->render('finance');
    }

    /**
     * 月度应付表订单状态更新
     */
    public function actionPurchase_order_update()
    {
        if (yii::$app->request->isPost) {
            $purchase_order = yii::$app->request->post('order');
            $status         = yii::$app->request->post('status');
            $model          = new Purchase_order();
            $re             = $model->update_status($purchase_order, $status);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败，请重试']);
            }
        }
    }

    /**
     * 业务员添加仓库费用记录
     */
    public function actionAdd_repo()
    {
        if (yii::$app->request->isPost) {
            $data         = yii::$app->request->post('data');
            $data['name'] = $this->user['job_number'];
            $model        = new Repo();
            $re           = $model->insert($data);
            if ($re) {
                //设置pid=id
                $sql = 'UPDATE jingsourcing_repo_fee set `pid`=`id` WHERE `pid`=0';
                yii::$app->db->createCommand($sql)->execute();
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
            }
        }
    }

    /**
     * 业务员添加
     */

    public function actionAdd_inland()
    {
        if (yii::$app->request->isPost) {
            $data            = yii::$app->request->post('data');
            $data['saleman'] = $this->user['job_number'];
            $model           = new Inland();
            $re              = $model->insert($data);
            $service         = new InlandService();
            $service->updatePid();
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
            }
        }
    }

    public function actionPrint()
    {
        $p = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        parse_str($_SERVER['QUERY_STRING'], $output);
        if (isset($output['p'])) {
            unset($output['p']);
        }
        if (isset($output['s'])) {
            unset($output['s']);
        }
        $where                  = [];
        $where['invoice_order'] = trim(yii::$app->request->get('invoice'));
        $where['begin_date']    = yii::$app->request->get('begin_date');
        $where['end_date']      = yii::$app->request->get('end_date');
        $where['name']          = yii::$app->request->get('name');
        $model                  = new PrintModel();
        $list                   = $model->all($where, ($p - 1) * $s, $s, ['date' => SORT_DESC, 'id' => SORT_DESC]);
        foreach ($list as $k => $v) {
            $list[$k]['last_modify_time'] = $v['last_modify_time'] ? date('Y-m-d H:i:s', $v['last_modify_time']) : '';
        }
        $size                                = $model->size($where);
        $model                               = new Staff();
        $staffList                           = $model->get_all_saleman();
        yii::$app->view->params['base_url']  = '/table/print?' . http_build_query($output);
        yii::$app->view->params['size']      = $size;
        yii::$app->view->params['curr']      = $p;
        yii::$app->view->params['s']         = $s;
        yii::$app->view->params['staffList'] = $staffList;
        yii::$app->view->params['list']      = $list;
        return $this->render('print');
    }

    public function actionPrintList()
    {
        $p                      = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                      = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where                  = [];
        $where['invoice_order'] = trim(yii::$app->request->get('invoice'));
        $where['begin_date']    = yii::$app->request->get('beginTime');
        $where['end_date']      = yii::$app->request->get('endTime');
        $where['name']          = yii::$app->request->get('staff');
        $model                  = new PrintModel();
        $list                   = $model->all($where, ($p - 1) * $s, $s, ['date' => SORT_DESC, 'id' => SORT_DESC]);
        $size                   = $model->size($where);
        return json_encode(['list' => $list, 'total' => $size]);

    }

    public function actionPrintBase()
    {
        $model     = new Staff();
        $staffList = $model->get_all_saleman();
        return json_encode(['staff' => $staffList]);
    }

    public function actionUpdatePrint()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $model = new PrintModel();
            $re    = $model->one(['id' => $id]);
            if ($re['lock_status'] == 1) {
                echo json_encode(['code' => 0, 'msg' => '已被锁定无法修改']);
                exit;
            }
            $param                    = yii::$app->request->post('param');
            $value                    = yii::$app->request->post('value');
            $data                     = [];
            $data['last_modify']      = $this->user['job_number'];
            $data['last_modify_time'] = time();
            $data[$param]             = $value;
            $re                       = $model->save($data, ['id' => $id]);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '修改失败，请重试']);
            }
        }
    }

    public function actionDelPrint()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $model = new PrintModel();
            $re    = $model->one(['id' => $id]);
            if ($re['lock_status'] == 1) {
                echo json_encode(['code' => 0, 'msg' => '已被锁定无法修改']);
                exit;
            }
            $re = $model->delete(['id' => $id]);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '删除成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '删除失败，请重试']);
            }
        }
    }

    /**
     **/
    public function actionLockPrint()
    {
        if (yii::$app->request->isPost) {
            $id    = yii::$app->request->post('id');
            $param = yii::$app->request->post('param');
            $value = yii::$app->request->post('value');
            $model = new PrintModel();
            $re    = $model->save([$param => $value], ['id' => $id]);
            if ($re) {
                echo json_encode(['code' => 1, 'msg' => '更新成功']);
            } else {
                echo json_encode(['code' => 0, 'msg' => '更新失败，请重试']);
            }
        }
    }

    public function actionInrepoList()
    {
        $p                   = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                   = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where               = [];
        $where['staff']      = yii::$app->request->get('staff');
        $where['number_no']  = yii::$app->request->get('number_no');
        $where['status']     = yii::$app->request->get('status');
        $where['begin_time'] = yii::$app->request->get('begin_time');
        $where['end_time']   = yii::$app->request->get('end_time');
        $model               = new InRepo();

        $list = $model->all($where, ($p - 1) * $s, $s, ['date' => SORT_DESC, 'id' => SORT_DESC]);
        $size = $model->size($where);
        echo json_encode(['list' => $list, 'size' => $size]);
    }

    public function actionInrepoRegionList()
    {
        $p                   = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                   = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where               = [];
        $where['staff']      = yii::$app->request->get('staff');
        $where['number_no']  = yii::$app->request->get('number_no');
        $where['status']     = yii::$app->request->get('status');
        $where['begin_time'] = yii::$app->request->get('begin_time');
        $where['end_time']   = yii::$app->request->get('end_time');
        $model               = new InrepoLock();

        $list = $model->all($where, ($p - 1) * $s, $s, ['date' => SORT_DESC, 'id' => SORT_DESC]);
        $size = $model->size($where);
        echo json_encode(['list' => $list, 'size' => $size]);
    }

    public function actionInrepoBase()
    {
        $model     = new Staff();
        $staffList = $model->get_all_saleman();
        return json_encode(['staff' => $staffList]);

    }

    /**入库上传数据
     * @return string
     * @throws yii\db\Exception
     */
    public function actionInrepoUpload()
    {
        $rules = ['date', 'express_fee', 'name'];
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法请求方式']);
        }
        $data = yii::$app->request->post();
        $re   = $this->validateRules($rules);
        if (!$re) {
            return json_encode(['code' => 0, 'msg' => '参数不全']);
        }
        $model = new InRepo();
        //添加入库编号
        //获取今天最后一个编号
        $info   = $model->getNumber();
        $number = (int) $info['number_no'];
        $number++;
        $data['number_no']   = $info ? $number : date('ymd') . '001';
        $data['express_fee'] = !empty($data['express_fee']) ? $data['express_fee'] : 0;
        $data['unload_fee']  = !empty($data['unload_fee']) ? $data['unload_fee'] : 0;
        $data['other_fee']   = !empty($data['other_fee']) ? $data['other_fee'] : 0;
        $data['time']        = time();
        $data['repo_staff']  = $this->user['job_number'];
        $data['region_num']  = $data['num'] + (int) $data['box'] * (int) $data['carton'];
        try {
            $model2 = new InrepoLock();
            $model2->insert($data);
            if ($model->insert($data)) {
                return json_encode(['code' => 1, 'msg' => '添加成功']);
            } else {
                return json_encode(['code' => 0, 'msg' => '添加失败，请重试']);
            }
        } catch (\Exception $e) {
            $error = $e->getMessage();
            return json_encode(['code' => 0, 'msg' => $error]);
        }

    }

    /**产品出库
     * @return string
     * @throws yii\db\Exception
     */
    public function actionOutrepo()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法请求方式']);
        }
        $info = yii::$app->request->post();
        //记录出库日志
        $type               = (int) $info['type'];
        $data               = [];
        $data['name']       = $type == 1 ? '出库' : '货物损坏';
        $data['date']       = date('Y-m-d');
        $data['box']        = $info['box'];
        $data['carton']     = $info['carton'];
        $data['num']        = $info['num'];
        $data['inrepo_id']  = $info['id'];
        $data['repo_staff'] = $this->user['job_number'];
        $data['remark']     = $info['remark'];
        $data['length']     = $info['length'];
        $data['width']      = $info['width'];
        $data['height']     = $info['height'];
        $data['time']       = time();
        //检查出库数量是否大于库存
        $db   = new InRepo();
        $info = $db->one(['id' => $data['inrepo_id']]);
        if ((int) $info['num'] < (int) $data['num']) {
            return json_encode(['code' => 0, 'msg' => '出库数量不得大于库存数量']);
        }
        $model = new InrepoLog();
        try {
            //记录日志
            $re = $model->insert($data);
            //修改原始数据
            if ($type == 1) {
                $sql = 'UPDATE jingsourcing_in_repo SET `num`=`num`-:num,`out_num`=`out_num`+ :out_num WHERE `id`=:id';
                yii::$app->db->createCommand($sql, ['num' => (int) $data['num'], 'out_num' => (int) $data['num'], 'id' => (int) $info['id']])->execute();
            } else {
                $sql        = 'UPDATE jingsourcing_in_repo SET `num`=`num`-:num,`bad_num`=`bad_num`+ :bad_num WHERE `id`=:id';
                $bindValues = ['num' => (int) $data['num'], 'bad_num' => (int) $data['num'], 'id' => $info['id']];
                yii::$app->db->createCommand($sql, $bindValues)->execute();
            }

            if ($re) {
                return json_encode(['code' => 1, 'msg' => '添加成功,等待财务审核']);
            } else {
                return json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
            }
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            return json_encode(['code' => 0, 'msg' => $msg]);
        }
    }

    public function actionInrepoEdit()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法请求']);
        }

        $info = yii::$app->request->post();
        $id   = $info['id'];
        unset($info['id']);
        $model = new InRepo();
        $tr    = yii::$app->db->beginTransaction();
        try {
            //复制当前记录到日志边
            $data = $model->one(['id' => $id]);
            unset($data['id']);
            $insertModal = new InrepoEdit();
            $insertModal->insert($data);
            $re = $model->save($info, ['id' => $id]);
            $tr->commit();
            if ($re) {
                return json_encode(['code' => 1, 'msg' => '修改成功']);
            } else {
                return json_encode(['code' => 0, 'msg' => '修改失败,请重试']);
            }
        } catch (\Exception $e) {
            $tr->rollBack();
            $msg = $e->getMessage();
            return json_encode(['code' => 0, 'msg' => $msg]);
        }

    }

    public function actionInrepoVerifyList()
    {
        $p                   = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                   = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where               = [];
        $where['status']     = yii::$app->request->get('status');
        $where['begin_time'] = yii::$app->request->get('begin_time');
        $where['end_time']   = yii::$app->request->get('begin_time');
        $model               = new InrepoLog();
        $list                = $model->all($where, ($p - 1) * $s, $s, ['time' => SORT_DESC]);
        $repoId              = array_column($list, 'inrepo_id');
        $InrepoModel         = new Inrepo();
        $list2               = $InrepoModel->all(['id' => $repoId]);
        //合并list
        foreach ($list as $k => $v) {
            foreach ($list2 as $v2) {
                if ($v['inrepo_id'] = $v2['id']) {
                    $list[$k]['product_name'] = $v2['name'];
                }
            }
        }
        $size = $model->size($where);
        return json_encode(['list' => $list, 'size' => $size]);
    }

    public function actionVerifyEdit()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => '非法请求']);
        }
        $id                   = yii::$app->request->post('id');
        $invoice              = yii::$app->request->post('invoice');
        $model                = new InrepoLog();
        $data                 = [];
        $data['verify_staff'] = $this->user['job_number'];
        $data['status']       = 2;
        $data['time']         = time();
        $data['invoice']      = $invoice;
        if ($model->save($data, ['id' => $id])) {
            return json_encode(['code' => 1, 'msg' => '添加成功']);
        } else {
            return json_encode(['code' => 0, 'msg' => '添加失败,请重试']);
        }
    }

    //基于invoice产品出库list
    public function actionOutputList()
    {
        $p                   = is_numeric(yii::$app->request->get('p')) ? yii::$app->request->get('p') : 1;
        $s                   = is_numeric(yii::$app->request->get('s')) ? yii::$app->request->get('s') : 15;
        $where               = [];
        $where['begin_time'] = yii::$app->request->get('begin_time');
        $where['end_time']   = yii::$app->request->get('end_time');
        $where['invoice']    = yii::$app->request->get('invoice');
        $where['staff']      = yii::$app->request->get('staff');
        $model               = new Invoice_new();
        $list                = $model->all($where, ($p - 1) * $s, $s, ['date' => SORT_DESC, 'id' => SORT_DESC]);
        $invoiceList         = array_column($list, 'invoice');
        //从审核成功的产品出库里面
        $model = new InrepoLog();
        $list2 = $model->all(['invoice' => $invoiceList, 'status' => 2]);
        foreach ($list as $k => $v) {
            foreach ($list2 as $v2) {
                if ($v['invoice'] == $v2['invoice']) {
                    $list[$k]['children'][] = $v2;
                }
            }
        }
        $staffModel = new Staff();
        $staff      = $staffModel->get_all_saleman();
        return json_encode(['list' => $list, 'staff' => $staff]);
    }

    public function actionRepoHistory()
    {
        $id    = yii::$app->request->get('id');
        $model = new InrepoLog();
        $list  = $model->all(['inrepo_id' => $id], false, false, ['id' => SORT_DESC]);
        return json_encode(['list' => $list]);
    }

    /**
     * 每月invoice收款详情
     */
    public function actionMonthInvoice()
    {
        $data                = yii::$app->request->get();
        $where               = [];
        $where['staff']      = $data['service_name'];
        $where['begin_time'] = $data['begin_time'];
        $where['end_time']   = $data['end_time'];
        //获取当月的invoice
        $model       = new Invoice_new();
        $invoiceList = $model->all($where);
        $invoiceArr  = array_column($invoiceList, 'invoice');
        $model       = new Income();
        $list        = $model->get_income_by_invoice($invoiceArr);
        $invoice     = [];
        foreach ($invoiceArr as $v) {
            $invoice[$v] = 0;
        }
        foreach ($list as $v) {
            $total = $v['in_come'] + $v['fee'] + $v['total_fee'];
            $invoice[$v['invocie_num']] += $total;
        }
        $output = [];
        foreach ($invoice as $k => $v) {
            foreach ($invoiceList as $k2 => $v2) {
                if ($k == $v2['invoice']) {
                    $tmp             = [];
                    $tmp['invoice']  = $k;
                    $tmp['need_pay'] = (float) $v2['order_pay'];
                    $tmp['have_pay'] = (float) $v;
                    $output[]        = $tmp;
                }
            }
        }

        return $this->render('month-invoice', ['list' => $output]);
    }

}
